package com.vframework.rest.resources;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.util.StringUtil;
import com.util.memcached.CacheUtil;
import com.vframework.rest.bean.SessionCache;
import com.vframework.rest.common.RestResponse;
import com.vframework.rest.util.EopConstant;

/***************************************************************
 * Name:        AuthResource.java
 * Create At:   2018年4月11日
 * Module:      
 * Description: [功能描述]
 * @author      shanzhitong
 * ------------------------------------------------------------
 * 修改历史
 * 序号         日期                       修改人               修改原因
 * 1    2018年4月11日      shanzhitong    
 * 2
***************************************************************/
@Component
@Path("auth")
public class AuthResource {
    @Autowired
    private CacheUtil cacheUtil;
    @Context
    private HttpServletRequest httpRequest;

    @Path("getToken")
    @GET
    @PermitAll
    @Produces(MediaType.APPLICATION_JSON)
    public Response getToken(ContainerRequestContext requestContext) {
        String token = requestContext.getHeaderString("Authorization");
//        String orgId = requestContext.getHeaderString("orgId");
//        if (StringUtil.isEmpty(orgId))
//            return Response.status(Response.Status.OK).entity(new RestResponse(RestResponse.Status.NOORG)).build();
        SessionCache sessionCache = cacheUtil.get(EopConstant.CACHE_TOKEN_KEY + token);
        if (sessionCache != null) {
            cacheUtil.set(EopConstant.CACHE_TOKEN_KEY + token, sessionCache, 60 * 24 * 7);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("token", token);
            return Response.status(Response.Status.OK).entity(new RestResponse(map)).build();
        }
        token = StringUtil.md5(UUID.randomUUID().toString());
        Map<String, Object> map = new HashMap<String, Object>();
        sessionCache = new SessionCache();
        sessionCache.setSessionId(token);
//        sessionCache.setOrgId(orgId);
        map.put("token", token);
//        // sessionid缓存7天
        cacheUtil.set(EopConstant.CACHE_TOKEN_KEY + token, sessionCache, 60 * 24 * 7);
        return Response.status(Response.Status.OK).entity(new RestResponse(map)).build();
    }
}
